<?php
/**
 * 左侧菜单树
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: MenuController.php 1082 2011-12-09 09:27:48Z maomao.thx@gmail.com $
 */
class System_MenuController extends IG_Controller_Action
{

    /**
     * 左侧菜单树列表
     * @author maomao.thx@gmail.com
     */
    public function listAction()
    {
        $menu = new System_Model_Menu();
        $this->view->assign('data', $menu->fetchAll(null, 'position')->toArray());
    }

    /**
     * 左侧菜单修改(增删改移)
     * @author maomao.thx@gmail.com
     */
    public function modifyAction()
    {
        $this->disableLayout();
        $this->setNoRender();
        $do = $this->_getParam('do');

        if (in_array($do, array('save', 'delete', 'move', 'resource')))
            $this->{"_$do"}();
    }

    protected function _save()
    {
        $params = $this->_getParam('params');
        $menu = new System_Model_Menu($params);
        $menu->save();
        $this->_helper->json(array('params' => $menu->toArray(), 'statusCode' => 0));
    }

    protected function _delete()
    {
        $id = $this->_getParam('id');
        $menu = new System_Model_Menu(array('id' => $id));
        $result = $menu->delete();
        $this->_helper->json(array('statusCode' => (int) !$result));
    }

    protected function _move()
    {
        $afterParent  = $this->_getParam('after_parent');
        $afterNode    = $this->_getParam('after_node');
        $beforeParent = $this->_getParam('before_parent');
        $current      = $this->_getParam('current');

        $menu = new System_Model_Menu();
        $afterNode = array_flip($afterNode);

        if (!empty($beforeParent)) {
            $menu->find($current)->setParentId($afterParent)->save();
        }

        foreach ($menu->fetchAll(array('parent_id=?' => $afterParent), 'position') as $key => $row) {
            if ($row->position == $afterNode[$row->id]) continue;
            $row->position = $afterNode[$row->id];
            $row->save();
        }

        $this->_helper->json(array('statusCode' => 0));
    }

    protected function _resource()
    {
        $url = $this->_getParam('url');
        $url = parse_url($url);

        $where = array();
        list(, $where['module=?'], $where['controller=?'], $where['action=?'])
             = explode('/', $url['path'])+array_fill(1, 3, 'index');

        $resource = new System_Model_Resource();

        $data = $resource->fetchAll($where);
        $id   = intval(count($data) ? $data[0]->getResourceId() : 0);

        $this->_helper->json(array('statusCode' => 0, 'id' => $id));
    }
}